//
//  LoginController.m
//  gdemm
//
//  Created by 乔明超 on 16/9/20.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "LoginController.h"
#import "RegisterController.h"
#import "SliderController.h"
#import "Masonry.h"
#import "Utils.h"
#import "Constants.h"
#import "ToastManager.h"
#import "DeviceInfo.h"
#import "DeviceInfoCommit.h"
#import "SVProgressHUD.h"
#import "KeyChain.h"
#import "RootChecker.h"
#import "MobileConfig.h"
#import "HeartBeat.h"
@interface LoginController ()<UITextFieldDelegate>
@property (strong,nonatomic) UIImageView    *mIvLogo;
@property (strong,nonatomic) UITextField    *mTvUserName;
@property (strong,nonatomic) UITextField    *mTvUserPasswd;
@property (strong,nonatomic) UIButton       *mBtnLogin;
@property (strong,nonatomic) UIButton       *mBtnRegister;
@property (nonatomic,strong) UIAlertController *alertController;
@property(nonatomic,strong) UIView *horizontalLineUserName ;
@property(nonatomic,strong) UIView *horizontalLinePassWd ;
@property(nonatomic,strong)UIImageView *imageUser;
@property(nonatomic,strong)UIImageView *imagePassWd;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)BOOL isSuccess;
@end

@implementation LoginController

#pragma mark - 懒加载

/*点击设置弹出IP设置alertView*/
- (UIAlertController *)alertController{
    
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"str_enterServerIP", @"请输入服务器IP") message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_ok", @"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            
            if ([[UserDefaultsUtil shareInstance]getString:LC_SERVADDR] == nil) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                });
            }
            UITextField * firstTextFileld = _alertController.textFields[ZERO];
            NSString *ipText = firstTextFileld.text;
            if (![StringUtil isIp:ipText]) {
                [self.view makeToast:NSLocalizedString(@"str_IllegalIPAddress", @"IP地址非法")];
                return;
            }
            [[UserDefaultsUtil shareInstance]saveStringConfig:LC_SERVADDR : ipText];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_cancel", @"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
            
        }];
        [_alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
            //在这里修改textField样式
            textField.keyboardType = UIKeyboardTypeDecimalPad;
            NSString *ip = [[UserDefaultsUtil shareInstance]getString:LC_SERVADDR];
            if (ip != nil) {
                textField.text = ip;
            }
            
        }];
        [_alertController addAction:confirm];
        [_alertController addAction:cancel];
    }
    
    return _alertController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化登录界面
    if ([DeviceTypeJudge isPadDeviceType]) {
        [self setupLoginView];
    }else{
    
        [self setupIPhoneLoginView];
    }
    //添加手势
    [self addGesture];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
     //IP设置框自动弹出
    NSString *ip = [[UserDefaultsUtil shareInstance]getString:LC_SERVADDR];
    if (ip == nil) {
        [self presentViewController:self.alertController animated:YES completion:nil];
    }
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    //获取已登录过得账号和密码
    NSString *username = [[UserDefaultsUtil shareInstance]getString:LC_USERNAME];
    NSString *password = [[UserDefaultsUtil shareInstance]getString:LC_PASSWORD];
    if (username != nil) {
        self.mTvUserName.text = username;
    }
    if (password != nil) {
        self.mTvUserPasswd.text = password;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
#pragma mark - 初始化登录界面

//ipad UI
- (void)setupLoginView{
    
    //设置View背景色
    self.view.backgroundColor = [Utils colorWithKey:@"loginBgColor"];
    //添加logo
    self.mIvLogo = [[UIImageView alloc]init];
    self.mIvLogo.image = [UIImage imageNamed:@"logo"];
    [self.mIvLogo sizeToFit];
    [self.view addSubview:self.mIvLogo];
    [self.mIvLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(118);
        make.height.mas_equalTo(184);
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(110);
    }];
    
    //线条
    UIView *horizontalLineUserName = [[UIView alloc]init];
    self.horizontalLineUserName = horizontalLineUserName;
    horizontalLineUserName.backgroundColor = [Utils UIColorFromHex:0X60afe4];
    //用户输入框
    UIImageView *imageUser = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
    self.imageUser = imageUser;
    imageUser.image = [Utils imageWithKey:@"loginUserName"];
    self.mTvUserName = [[UITextField alloc]init];
    self.mTvUserName.delegate = self;
    self.mTvUserName.attributedPlaceholder = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"str_username", "请输入用户名") attributes:@{NSForegroundColorAttributeName:[Utils colorWithKey:@"loginPlaceholderColor"],NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    [self.mTvUserName setFont:[UIFont systemFontOfSize:24]];
    [self.mTvUserName setTextColor:[Utils UIColorFromHex:0Xffffff]];
    self.mTvUserName.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.mTvUserName.autocorrectionType = UITextAutocorrectionTypeNo;
    self.mTvUserName.textColor = [Utils colorWithKey:@"loginTextColor"];
    [self.mTvUserName addTarget:self action:@selector(clearPassword) forControlEvents:UIControlEventEditingChanged];
    UIView *paddingView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 66, 30)];
    [paddingView addSubview:imageUser];
    self.mTvUserName.leftView = paddingView;
    self.mTvUserName.leftViewMode =  UITextFieldViewModeAlways;
    self.mTvUserName.returnKeyType = UIReturnKeyNext;
    
    [self.view addSubview:self.mTvUserName];
    [self.view addSubview:horizontalLineUserName];
    [self.mTvUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(360);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(self.mIvLogo.mas_bottom).offset(140);
    }];
    [horizontalLineUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(360);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(19);
    }];
    
    
    //线条
    UIView *horizontalLinePassWd = [[UIView alloc]init];
    self.horizontalLinePassWd = horizontalLinePassWd;
    horizontalLinePassWd.backgroundColor = [Utils UIColorFromHex:0X60afe4];
    //密码框
    UIImageView *imagePassWd = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
    self.imagePassWd = imagePassWd;
    imagePassWd.image = [Utils imageWithKey:@"loginPassWord"];
    self.mTvUserPasswd = [[UITextField alloc]init];
    self.mTvUserPasswd.delegate = self;
    self.mTvUserPasswd.attributedPlaceholder = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"str_password", "请输入密码") attributes:@{NSForegroundColorAttributeName:[Utils colorWithKey:@"loginPlaceholderColor"],NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    [ self.mTvUserPasswd setFont:[UIFont systemFontOfSize:24]];
    [self.mTvUserPasswd setTextColor:[Utils colorWithKey:@"loginTextColor"]];
    self.mTvUserPasswd.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.mTvUserPasswd.autocorrectionType = UITextAutocorrectionTypeNo;
    self.mTvUserPasswd.secureTextEntry = YES;
    UIView *paddingViewPass = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 66, 30)];
    [paddingViewPass addSubview:imagePassWd];
    self.mTvUserPasswd.leftView = paddingViewPass;
    self.mTvUserPasswd.leftViewMode = UITextFieldViewModeAlways;
    self.mTvUserPasswd.returnKeyType = UIReturnKeyNext;
    [self.view addSubview:self.mTvUserPasswd];
    [self.view addSubview:horizontalLinePassWd];
    [self.mTvUserPasswd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(360);
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(68);
    }];
    
    [horizontalLinePassWd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(360);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(19);
    }];
    
    //添加登录按钮
    self.mBtnLogin = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self.mBtnLogin setBackgroundImage:[Utils imageWithKey:@"loginBtnNormal"] forState:UIControlStateNormal];
    [self.mBtnLogin setBackgroundImage:[Utils imageWithKey:@"loginBtnHighlighted"] forState:UIControlStateHighlighted];
    [self.mBtnLogin setTitle:NSLocalizedString(@"str_login", @"登录") forState:UIControlStateNormal];
    [self.mBtnLogin setTitleColor:[Utils UIColorFromHex:0Xffffff] forState:UIControlStateNormal];
    [self.mBtnLogin setTitleColor:[Utils UIColorFromHex:0Xffffff] forState:UIControlStateHighlighted];
    self.mBtnLogin.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.mBtnLogin addTarget:self action:@selector(loginHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mBtnLogin];
    [self.mBtnLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(360);
        make.height.mas_equalTo(48);
        make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(86);
    }];
    
    //添加注册按钮
    self.mBtnRegister = [UIButton buttonWithType:UIButtonTypeSystem];
    self.mBtnRegister.layer.cornerRadius = 6;
    self.mBtnRegister.layer.borderWidth = 0.5;
    self.mBtnRegister.layer.borderColor = [[Utils colorWithKey:@"loginBtnRegisterColor"]CGColor];
    [self.mBtnRegister setTitle:NSLocalizedString(@"str_register", @"注册") forState:UIControlStateNormal];
    [self.mBtnRegister setTitleColor:[Utils colorWithKey:@"loginBtnRegisterColor"] forState:UIControlStateNormal];
    self.mBtnRegister.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.mBtnRegister addTarget:self action:@selector(registerHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mBtnRegister];
    [self.mBtnRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(360);
        make.height.mas_equalTo(48);
        make.top.mas_equalTo(self.mBtnLogin.mas_bottom).offset(20);
    }];
    
}

//iPhone UI
- (void)setupIPhoneLoginView{
    
    //设置View背景色
    self.view.backgroundColor = [Utils colorWithKey:@"loginBgColor"];
    //添加logo
    self.mIvLogo = [[UIImageView alloc]init];
    self.mIvLogo.image = [Utils getImageByDevce:@"logo"];
    [self.mIvLogo sizeToFit];
    [self.view addSubview:self.mIvLogo];
    [self.mIvLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(73*KWidthScale);
        make.height.mas_equalTo(114*KHeightScale);
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(62*KHeightScale);
    }];
    
    //线条
    UIView *horizontalLineUserName = [[UIView alloc]init];
    self.horizontalLineUserName = horizontalLineUserName;
    horizontalLineUserName.backgroundColor = [Utils UIColorFromHex:0X60afe4];
    //用户输入框
    UIImageView *imageUser = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    self.imageUser = imageUser;
    imageUser.image = [Utils imageWithKey:@"loginUserName"];
    self.mTvUserName = [[UITextField alloc]init];
    self.mTvUserName.delegate = self;
    self.mTvUserName.attributedPlaceholder = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"str_username", "请输入用户名") attributes:@{NSForegroundColorAttributeName:[Utils colorWithKey:@"loginPlaceholderColor"],NSFontAttributeName:[UIFont systemFontOfSize:8]}];
    [self.mTvUserName setFont:[UIFont systemFontOfSize:10]];
    [self.mTvUserName setTextColor:[Utils UIColorFromHex:0Xffffff]];
    self.mTvUserName.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.mTvUserName.autocorrectionType = UITextAutocorrectionTypeNo;
    self.mTvUserName.textColor = [Utils colorWithKey:@"loginTextColor"];
    [self.mTvUserName addTarget:self action:@selector(clearPassword) forControlEvents:UIControlEventEditingChanged];
    UIView *paddingView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 31, 22)];
    [paddingView addSubview:imageUser];
    self.mTvUserName.leftView = paddingView;
    self.mTvUserName.leftViewMode =  UITextFieldViewModeAlways;
    self.mTvUserName.returnKeyType = UIReturnKeyNext;
    
    [self.view addSubview:self.mTvUserName];
    [self.view addSubview:horizontalLineUserName];
    [self.mTvUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(175*KWidthScale);
        make.height.mas_equalTo(22);
        make.top.mas_equalTo(self.mIvLogo.mas_bottom).offset(58*KHeightScale);
    }];
    [horizontalLineUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(175*KWidthScale);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(9);
    }];
    
    
    //线条
    UIView *horizontalLinePassWd = [[UIView alloc]init];
    self.horizontalLinePassWd = horizontalLinePassWd;
    horizontalLinePassWd.backgroundColor = [Utils UIColorFromHex:0X60afe4];
    //密码框
    UIImageView *imagePassWd = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    self.imagePassWd = imagePassWd;
    imagePassWd.image = [Utils imageWithKey:@"loginPassWord"];
    self.mTvUserPasswd = [[UITextField alloc]init];
    self.mTvUserPasswd.delegate = self;
    self.mTvUserPasswd.attributedPlaceholder = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"str_password", "请输入密码") attributes:@{NSForegroundColorAttributeName:[Utils colorWithKey:@"loginPlaceholderColor"],NSFontAttributeName:[UIFont systemFontOfSize:8]}];
    [self.mTvUserPasswd setFont:[UIFont systemFontOfSize:10]];
    [self.mTvUserPasswd setTextColor:[Utils colorWithKey:@"loginTextColor"]];
    self.mTvUserPasswd.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.mTvUserPasswd.autocorrectionType = UITextAutocorrectionTypeNo;
    self.mTvUserPasswd.secureTextEntry = YES;
    UIView *paddingViewPass = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 31, 22)];
    [paddingViewPass addSubview:imagePassWd];
    self.mTvUserPasswd.leftView = paddingViewPass;
    self.mTvUserPasswd.leftViewMode = UITextFieldViewModeAlways;
    self.mTvUserPasswd.returnKeyType = UIReturnKeyNext;
    [self.view addSubview:self.mTvUserPasswd];
    [self.view addSubview:horizontalLinePassWd];
    [self.mTvUserPasswd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(175*KWidthScale);
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(22);
        make.top.mas_equalTo(self.horizontalLineUserName.mas_bottom).offset(28*KHeightScale);
    }];
    
    [horizontalLinePassWd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(175*KWidthScale);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(9);
    }];
    
    //添加登录按钮
    self.mBtnLogin = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self.mBtnLogin setBackgroundImage:[Utils imageWithKey:@"loginBtnNormal"] forState:UIControlStateNormal];
    [self.mBtnLogin setBackgroundImage:[Utils imageWithKey:@"loginBtnHighlighted"] forState:UIControlStateHighlighted];
    [self.mBtnLogin setTitle:NSLocalizedString(@"str_login", @"登录") forState:UIControlStateNormal];
    [self.mBtnLogin setTitleColor:[Utils UIColorFromHex:0Xffffff] forState:UIControlStateNormal];
    [self.mBtnLogin setTitleColor:[Utils UIColorFromHex:0Xffffff] forState:UIControlStateHighlighted];
    self.mBtnLogin.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.mBtnLogin addTarget:self action:@selector(loginHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mBtnLogin];
    [self.mBtnLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(175*KWidthScale);
        make.height.mas_equalTo(30*KHeightScale);
        make.top.mas_equalTo(self.horizontalLinePassWd.mas_bottom).offset(28*KHeightScale);
    }];
    
    //添加注册按钮
    self.mBtnRegister = [UIButton buttonWithType:UIButtonTypeSystem];
    self.mBtnRegister.layer.cornerRadius = 3;
    self.mBtnRegister.layer.borderWidth = 0.5;
    self.mBtnRegister.layer.borderColor = [[Utils colorWithKey:@"loginBtnRegisterColor"]CGColor];
    [self.mBtnRegister setTitle:NSLocalizedString(@"str_register", @"注册") forState:UIControlStateNormal];
    [self.mBtnRegister setTitleColor:[Utils colorWithKey:@"loginBtnRegisterColor"] forState:UIControlStateNormal];
    self.mBtnRegister.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.mBtnRegister addTarget:self action:@selector(registerHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mBtnRegister];
    [self.mBtnRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(175*KWidthScale);
        make.height.mas_equalTo(30*KHeightScale);
        make.top.mas_equalTo(self.mBtnLogin.mas_bottom).offset(28*KHeightScale);
    }];
    
}

#pragma mark - 添加手势
- (void)addGesture{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureHandler:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTapGestureHandler:)];
    doubleTap.numberOfTapsRequired = 2;
    doubleTap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:doubleTap];
    
}

#pragma mark - 登录按钮提交后的操作
- (void)loginHandler:(UIButton *)sender{
    [self.view endEditing:YES];
    NSString *userName = _mTvUserName.text;
    NSString *password = _mTvUserPasswd.text;
    if ([StringUtil isEmpty:userName]||[StringUtil isEmpty:password]) {
        [self.view makeToast:NSLocalizedString(@"str_usernameOrPasswordNotEmpty", @"用户名或密码不能为空")];
        return;
    }
    //检测描述文件是否安装
    if ([MobileConfig IsMobileConfigInstalled]) {

        [self loginWithUserName:userName andPassWd:password];
        
    }else{
        
        [self.view makeToast:NSLocalizedString(@"str_MobileConfigUnInstallation", @"描述文件未安装,3秒后自动安装描述文件")];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [NSThread sleepForTimeInterval:3.0];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkMobileConfig:) userInfo:nil repeats:YES];
                [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
            });
            NSString *uuidStr = [ApiSupport generateMobileConfigUrl];
            NSMutableDictionary *uuidDict = (NSMutableDictionary *)[KeyChain load:KEY_SERVICENAME];
            NSString *uuid = uuidDict[KEY_UUID];
            //设置参数
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"uuid"] = uuid;
            [params setValue:[[UIDevice currentDevice] model] forKey:@"unitType"];
            [params setValue:[NSString stringWithFormat:@"%@%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]] forKey:@"OS"];
            [params setValue:[DeviceInfo getIpAddress] forKey:@"ip"];
            [params setValue:[DeviceInfo getCPU] forKey:@"cpu"];
            [params setValue:[DeviceInfo getScreenSize] forKey:@"screenSize"];
            [params setValue:[DeviceInfo getResolution] forKey:@"resolution"];
            [params setValue:[DeviceInfo getPriCamera] forKey:@"postPixel"];
            [params setValue:[DeviceInfo getSecCamera] forKey:@"frontPixel"];
            [params setValue:[NSString stringWithFormat:@"%@",[NSNumber numberWithBool:[[RootChecker getInstance]isRoot]]] forKey:@"rootState"];
            [params setValue:@"0" forKey:@"devState"];
            NSData *data = [HttpUtil httpRequestSyncWithUrl:uuidStr andParams:params];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            HRLog(@"dict = %@",dict);
            if ([dict[@"status"] isEqualToString:@"success"]) {
                NSString *mobilePath = [ApiSupport installMobileConfigUrl];
                HRLog(@"mobile ==== %@",mobilePath);
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:mobilePath]];
            }else{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.view makeToast:NSLocalizedString(@"str_genMobileConfigFailed", @"描述文件生成失败,请退出重新登录")];
                });
            }
        });
    }
    
}

/**
 用户登录验证

 @param userName 用户名
 @param passWd 密码
 */
-(void)loginWithUserName:(NSString*)userName andPassWd:(NSString*)passWd{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:@"正在登录中..."];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    const  char *str = [passWd UTF8String];
    long len = strlen(str);
    unsigned const  char out_bf[65];
    sm3_buffer((void *)str, (int)len, (void *)out_bf, 32);
    [dict setValue:userName forKey:@"username"];
    [dict setValue:[NSString stringWithUTF8String:(void *)out_bf] forKey:@"password"];
    [dict setValue:[DeviceInfo getIpAddress] forKey:@"loginIp"];
    [dict setValue:[KeyChain getUDID] forKey:@"serial"];
    NSString *s = [HttpUtil buildUrl:[ApiSupport getUserLoginUrl] WithParams:dict];
    NSURL *url = [NSURL URLWithString:s];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc]initWithURL:url];
    [request startAsynchronous];
    request.delegate = self;
}


/**
 用户登录验证返回数据

 @param response 返回的数据
 */
-(void)parseResponseWithData:(NSData*)response{
    NSError *error;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    NSLog(@"登录返回值 == %@",dict);
    NSString *result = [dict objectForKey:@"result"];
    if ([result isEqualToString:@"success"]) {
        NSDictionary *userInfo = [dict objectForKey:@"userInfo"];
        NSString *userGuid = [userInfo objectForKey:@"userGUID"];
        NSString *trueName = [userInfo objectForKey:@"trueName"];
        [[UserDefaultsUtil shareInstance]saveBoolConfig:LC_MANUALLOGIN :true];
        [[UserDefaultsUtil shareInstance]saveBoolConfig:LC_HBOFFLINE :false];
        [[UserDefaultsUtil shareInstance]saveBoolConfig:LC_HBFAILED :false];
        [[UserDefaultsUtil shareInstance]saveBoolConfig:LC_LOGINED :true];
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_USERGUID :userGuid ];
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_TRUENAME :trueName ];
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_USERNAME :self.mTvUserName.text];
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_PASSWORD :self.mTvUserPasswd.text];
        [SVProgressHUD dismiss];
        [self.navigationController pushViewController:[[SliderController alloc]init] animated:YES];
    } else {
        [SVProgressHUD dismiss];
        NSString *err = [dict objectForKey:@"errCode"];
        
        if ([err isEqualToString:@"mismatch"]) {
            [self.view makeToast:NSLocalizedString(@"str_mismatch", @"用户与该设备不匹配")];
            return;
        }
        switch ([err intValue]) {
            case 1:
                [self.view makeToast:NSLocalizedString(@"str_emptyUserNameOrPswd", @"用户名或密码为空")];
                break;
            case 2:
                [self.view makeToast:NSLocalizedString(@"str_alreadyLogined", @"您已经登录，无须重复登录")];
                break;
            case 3:
                [self.view makeToast:NSLocalizedString(@"str_userNotFound", @"用户不存在")];
                break;
            case 4:
                [self.view makeToast:NSLocalizedString(@"str_pswdWrong", @"密码错误")];
                break;
            case 5:
                [self.view makeToast:NSLocalizedString(@"str_userNeedApprove", @"该用户尚未通过审核，请与管理员联系")];
                break;
            case 6:
                [self.view makeToast:NSLocalizedString(@"str_deviceNotActive", @"设备未激活")];
                break;
            case 7:
                [self.view makeToast:NSLocalizedString(@"str_deviceIsForbidden", @"设备已禁用")];
                break;
            case 8:
                //[self.view makeToast:NSLocalizedString(@"str_deviceNotRegist", @"设备未注册，请先进行设备注册后再登陆!")];
                //提交设备信息
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[DeviceInfoCommit shareInstance]commit];
                });
                break;
        }
    }
}

//注册按钮响应
- (void)registerHandler:(UIButton *)sender{
    RegisterController *registerVC = [[RegisterController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
}
//手势相应
- (void)tapGestureHandler:(UITapGestureRecognizer *)sender{
    [self.view endEditing:YES];
}

- (void)doubleTapGestureHandler:(UITapGestureRecognizer *)sender{
    [self.view endEditing:YES];
    [self presentViewController:self.alertController animated:YES completion:nil];
}

#pragma mark - ASIHTTPRequestDelegate
-(void)requestFailed:(ASIHTTPRequest *)request{
    [self.view makeToast:NSLocalizedString(@"str_loginFailed", @"登录失败")];
    [SVProgressHUD dismiss];
    
}
-(void)requestFinished:(ASIHTTPRequest *)request{
    
    [self parseResponseWithData:request.responseData];
    
}


#pragma mark - 检测描述文件是否安装完毕
- (void)checkMobileConfig:(NSTimer *)timer{
    if (_isSuccess) {
        return;
    }
    if ([MobileConfig IsMobileConfigInstalled]) {
        [self.timer invalidate];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString *getUDIDUrl = [ApiSupport saveUniqueUDIDURl];
            
            while (!_isSuccess) {
                [NSThread sleepForTimeInterval:1.0];
                NSDictionary *dict  = [HttpUtil httpGet:getUDIDUrl];
                
                if ([dict[@"status"]isEqualToString:@"success"]) {
                    
                    NSString *udid = [NSString stringWithFormat:@"%@",dict[@"udid"]];
                    if (udid.length != 0) {
                        NSMutableDictionary *keyDict = (NSMutableDictionary *)[KeyChain load:KEY_SERVICENAME];
                        keyDict[KEY_UDID] = dict[@"udid"];
                        [KeyChain save:KEY_SERVICENAME data:keyDict];
                        HRLog(@" UDID = %@  dic = %@  res = %@",[KeyChain  getUDID],dict[@"udid"],dict);
                        [[DeviceInfoCommit shareInstance]commit];
                        self.isSuccess = YES;
                    }
                }
            }
        });
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -输入框的代理方法
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField == self.mTvUserName) {
        
        if ([DeviceTypeJudge isPadDeviceType]) {
            [self.horizontalLineUserName mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(360);
                make.height.mas_equalTo(2);
                make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(19);
            }];
            self.imageUser.frame = CGRectMake(0, 0, 30, 30);
            
        }else{
            
            [self.horizontalLineUserName mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(175*KWidthScale);
                make.height.mas_equalTo(1.5);
                make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(8);
            }];
            self.imageUser.frame = CGRectMake(0, 0, 22, 22);
        }
        self.imageUser.image = [Utils imageWithKey:@"loginUserNamePre"];
    }else{
        
        if ([DeviceTypeJudge isPadDeviceType]) {
            [self.horizontalLinePassWd mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(360);
                make.height.mas_equalTo(2);
                make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(19);
            }];
            self.imagePassWd.frame = CGRectMake(0, 0, 30, 30) ;
        }else{
        
            [self.horizontalLinePassWd mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(175*KWidthScale);
                make.height.mas_equalTo(1.5);
                make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(8);
            }];
            self.imagePassWd.frame = CGRectMake(0, 0, 22, 22) ;
        }
        
        self.imagePassWd.image = [Utils imageWithKey:@"loginPassWordPre"];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
   [self.view endEditing:YES];
    if (textField == self.mTvUserName) {
        
        if ([DeviceTypeJudge isPadDeviceType]) {
            [self.horizontalLineUserName mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(360);
                make.height.mas_equalTo(1);
                make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(19);
            }];
            self.imageUser.frame = CGRectMake(0, 0, 22, 22);
        }else{
            [self.horizontalLineUserName mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(175*KWidthScale);
                make.height.mas_equalTo(1);
                make.top.mas_equalTo(self.mTvUserName.mas_bottom).offset(9);
            }];
            self.imageUser.frame = CGRectMake(0, 0, 20, 20);
        }
        
        self.imageUser.image = [Utils imageWithKey:@"loginUserName"];
    }else{
        if ([DeviceTypeJudge isPadDeviceType]) {
            [self.horizontalLinePassWd mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(360);
                make.height.mas_equalTo(1);
                make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(19);
            }];
            self.imagePassWd.frame = CGRectMake(0, 0, 22, 22) ;
        }else{
        
            [self.horizontalLinePassWd mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view);
                make.width.mas_equalTo(175*KWidthScale);
                make.height.mas_equalTo(1);
                make.top.mas_equalTo(self.mTvUserPasswd.mas_bottom).offset(9);
            }];
            self.imagePassWd.frame = CGRectMake(0, 0, 20, 20) ;
        }
        
        self.imagePassWd.image = [Utils imageWithKey:@"loginPassWord"];;
    }

}

-(void)clearPassword{
    self.mTvUserPasswd.text = nil;
}
@end
